﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.Security;
using System.Web.UI.WebControls;
using Marbles.CMS.ContentTypes;

namespace Marbles.CMS.Administrator.Content
{
    public partial class User : ContentEditorBase 
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            this.Title = "Edit User";

            if (!Page.IsPostBack)
            {
                InitialiseForm();
                LoadUser();
            }
        }

        private void InitialiseForm()
        {
            lstRoles.DataSource = Roles.GetAllRoles();
            lstRoles.DataBind();
        }

        private void LoadUser()
        {
            string uid = Request.Params["uid"];

            if (string.IsNullOrEmpty(uid))
            {
                this.Title = "Create User";
                btnSave.CommandName = "Insert";
                btnSave.CommandArgument = string.Empty;
                btnDelete.Visible = false;
                return;
            }


            txtUsername.Enabled = false;
            txtUsername.ReadOnly = true;
            btnDelete.CommandArgument = uid;
            btnSave.CommandName = "Update";
            btnSave.CommandArgument = uid;

            MembershipUser u = Membership.GetUser(uid);
            if (u != null)
            {
                string[] roles = Roles.GetRolesForUser(uid);
                lstRoles.ClearSelection();

                foreach (string s in roles)
                {
                    foreach (ListItem item in lstRoles.Items)
                    {
                        if (item.Value == s) { item.Selected = true; break; }
                    }
                }

                txtComment.Text = u.Comment;
                txtEmail.Text = u.Email;
                txtSecQuestion.Text = u.PasswordQuestion;
                txtUsername.Text = u.UserName;
                chkApproved.Checked = u.IsApproved;
                chkLocked.Checked = u.IsLockedOut;
                chkOnline.Checked = u.IsOnline;
                lblLastAct.Text = "Last Activity : " + u.LastActivityDate.ToShortDateString() + " " + u.LastActivityDate.ToShortTimeString();
            }
        }

        protected void btnSave_Command(object sender, CommandEventArgs e)
        {
            MembershipUser user = Membership.GetUser(e.CommandArgument.ToString());

            switch (e.CommandName)
            {
                case "Insert":
                    MembershipCreateStatus status = MembershipCreateStatus.Success;
                    Membership.CreateUser(txtUsername.Text, txtOldPassword.Text, txtEmail.Text, txtSecQuestion.Text, txtSecAnswer.Text, chkApproved.Checked, out status);

                    foreach (ListItem item in lstRoles.Items)
                    {
                        if (item.Selected) { 
                            if (!Roles.IsUserInRole(item.Value)) {Roles.AddUserToRole(txtUsername.Text, item.Value);} 
                        } else {
                            if (Roles.IsUserInRole(item.Value)) { Roles.RemoveUserFromRole(txtUsername.Text, item.Value); }
                        }
                    }
                    break;
                case "Update":
                    user.Comment = txtComment.Text;
                    user.IsApproved = chkApproved.Checked;
                    user.Email = txtEmail.Text;

                    Membership.UpdateUser(user);


                    foreach (ListItem item in lstRoles.Items)
                    {
                        if (item.Selected)
                        {
                            if (!Roles.IsUserInRole(item.Value)) { Roles.AddUserToRole(txtUsername.Text, item.Value); }
                        }
                        else
                        {
                            if (Roles.IsUserInRole(item.Value)) { Roles.RemoveUserFromRole(txtUsername.Text, item.Value); }
                        }
                    }

                    if (!chkLocked.Checked) { user.UnlockUser(); }
                    if (!string.IsNullOrEmpty(txtNewPassword.Text.Trim())) { user.ChangePassword(txtOldPassword.Text, txtNewPassword.Text); }

                    if ((user.PasswordQuestion != txtSecQuestion.Text) || (!string.IsNullOrEmpty(txtSecAnswer.Text)))
                    {
                        user.ChangePasswordQuestionAndAnswer(txtOldPassword.Text, txtSecQuestion.Text, txtSecAnswer.Text);
                    }

                    Membership.UpdateUser(user);
                    break;
                case "Delete":
                    Membership.DeleteUser(e.CommandArgument.ToString());
                    break;
            }

            Response.Redirect("Default.aspx?action=UserList", true);
        }

    }
}